#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import platform
import glob
import json
from ansible.module_utils import common_utils
from ansible.module_utils.basic import AnsibleModule


class NpuExporterUninstaller:

    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.messages = []

    def _module_failed(self):
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        return self.module.exit_json(msg="Uninstall npu-exporter success.", rc=0, changed=True)
    
    def stop_service(self):
        self.module.run_command(["systemctl", "stop", "npu-exporter"])
        self.module.run_command(["systemctl", "stop", "npu-exporter.timer"])
       
    
    def remove_file(self):
        files = [
            "/etc/systemd/system/npu-exporter.service",
            "/etc/systemd/system/npu-exporter.timer",
            "/usr/local/bin/npu-exporter"
        ]
        for file in files:
            if os.path.exists(file):
                self.module.run_command(["rm", "-rf", file])

    def run(self):
        try:
            self.stop_service()
            self.remove_file()
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    NpuExporterUninstaller().run()


if __name__ == "__main__":
    main()